package com.qf.shopping.controll;

import com.qf.shopping.Realm.MyRealm;
import com.qf.shopping.pojo.System.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;

@Controller
@SessionAttributes("user")
public class loginConrtoller {

    @GetMapping("/login")
    public  String tologin(){
        return "/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, HttpSession session,Model model,
                         String remember) {
        Boolean rememberMe=true;
        if (remember == null) {
            rememberMe=false;
        }
        System.out.println(rememberMe);
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,rememberMe);

        // 执行认证登陆
        try {
            subject.login(token);
            User user= (User) SecurityUtils.getSubject().getPrincipal();
            session.setAttribute("suser",user);
            return "redirect:/main";
        } catch (Exception e) {
            model.addAttribute("msg", e.getMessage());
            return "/login";
        }
    }

    @GetMapping("/logout")
    public  String logout(){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
//        //添加成功之后 清除缓存
//        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager)SecurityUtils.getSecurityManager();
//        MyRealm shiroRealm = (MyRealm) securityManager.getRealms().iterator().next();
//        //清除权限 相关的缓存
//        shiroRealm.clearAllCache();



        return "/login";
    }
}
